#include "outputwidget.h"
#include "ui_outputwidget.h"

OutputWidget::OutputWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OutputWidget)
{
    ui->setupUi(this);

    //初始化widget
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    //固定窗口大小
    setFixedSize(width(),height());
    //光标定位
    ui->lineEdit->setFocus();

    //初始化 combox
    QSqlQuery sqlResult;

    QString sqlQuery = "select stock_id from commodity_data";
    sqlResult.exec(sqlQuery);
    int i = 0;
    while(sqlResult.next())
    {
        //addItem()加在末尾 , insertItem() 指定加在某个位置
        ui->comboBox->addItem(sqlResult.value(0).toString());
        i++;
    }
}

OutputWidget::~OutputWidget()
{
    delete ui;
}

void OutputWidget::closeEvent(QCloseEvent *event)
{
    emit windowClosed();
    QWidget::closeEvent(event);
}

void OutputWidget::on_pushButton_exit_clicked()
{
    this->close();
}

void OutputWidget::on_pushButton_comDelivery_clicked()
{
    QSqlDatabase db = QSqlDatabase::database();

    if(!db.transaction())
    {
        QMessageBox::critical(this,"失败","开启事务失败,请重新检查！");
        return;
    }
    QSqlQuery sqlResult;
    try {
        QString deliveryCount = ui->lineEdit->text();
        QString deliveryTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString deliveryId = ui->comboBox->currentText();
        QString sqlUpdate = QString("update commodity_data"
                              " set stock_amount=stock_amount-%1,store_time='%2' where stock_id = %3").arg(deliveryCount).arg(deliveryTime).arg(deliveryId);
        qDebug() << sqlUpdate;
        if(sqlResult.exec(sqlUpdate))
        {
            QMessageBox::information(this,"成功","恭喜你,商品出库成功!");

            //同时将数据插入到汇总入库表
            //商品编号 商品名称 商品入库数量 商品数量 入库时间
            QString sqlQuery = QString("select stock_name,stock_amount from commodity_data where stock_id = %1").arg(deliveryId);
            sqlResult.exec(sqlQuery);
            QString deliveryName,allCount;
            sqlResult.next();
            deliveryName = sqlResult.value(0).toString();
            allCount = sqlResult.value(1).toString();

            //商品编号 商品名称 商品入库数量 商品数量 入库时间
            QString sqlDeliveryCom = QString("insert into commodity_delivery"
                                          " values (%1,'%2',%3,'%4','%5')").arg(deliveryId).arg(deliveryName).arg(deliveryCount).arg(allCount).arg(deliveryTime);
            qDebug() << sqlDeliveryCom;
            if(!sqlResult.exec(sqlDeliveryCom))
            {
                QMessageBox::information(this,"失败","输入插入到汇总出库表失败!");
                throw std::runtime_error("输入插入到汇总出库表失败!");
            }

        }
        else
        {
            QMessageBox::critical(this,"警告","商品出库失败,请重新检查...");
            throw std::runtime_error("商品出库失败,请重新检查...");

        }

        db.commit();
    } catch (...) {
        db.rollback();
        return;
    }

}
